﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;

namespace ClassProxitator.Messages
{
	public class ExceptionMessage: Message
	{
		public Exception Exception { get; set; }
		public int TaskId { get; set; }
		
		public override async Task<byte[]> GetContentBytes()
		{
			using (var s = new MemoryStream())
            {
                await s.WriteAsync(this.TaskId).ConfigureAwait(false);
                var bf = new BinaryFormatter();
                bf.Serialize(s, new Box(this.Exception));
                return s.ToArray();
            }
		}
		
		public override async Task LoadIn(Stream s)
		{
			this.TaskId = await s.ReadInt32Async().ConfigureAwait(false);
            var bf = new BinaryFormatter();
            this.Exception = ((Box)bf.Deserialize(s)).Data as Exception;
		}
		
		public override MessageType MessageType {
			get {
				return MessageType.Exception;
			}
		}
	}
}
